<template>
    <div class="sh_all">
        <div class="components_title">
            <TitleTop>
            </TitleTop>
            <TitleMenu>
                <div slot="titleMenu_ico" @click="jumpBack()">
                    <div class="title_left_ico">
                        <a-icon type="left" class="Group_ico" theme="outlined" />
                    </div>
                    <div class="title_left_text">返回</div>
                </div>
                <div slot="titleMenu_text" class="Homework_titleMenu_text">
                    <span>频道{{cName}}</span>
                </div>
                <!--<div slot="titleMenu_add">
                    <a-icon type="sync" style="font-size: 7vw;" theme="outlined" @click="refresh()" :class="[rotate?'go':'aa']" />
                </div>-->
            </TitleMenu>
        </div>

        <div id="groupAdd_content" style="height: calc(100vh - 66vw)">
            <!--头部功能图标导航栏-->
            <a-row class="manageChannel_title_row">
                <!--管理员增加频道成员按钮-->
                <a-col :span="24" class="manageChannel_title_col">
                    <Button type="info" icon="md-person-add" custom-icon="addUsersClass" @click="getCanAddUsersList" v-if="isCreator===true" style="padding: 1vw;font-size: 5vw;text-align: left">
                        邀请成员
                    </Button>
                    <Button type="info" icon="md-person-add" custom-icon="addUsersClass" @click="getCanAddUsersList" v-else disabled style="padding: 1vw;font-size: 5vw;text-align: left">
                        邀请成员
                    </Button>
                </a-col>
            </a-row>

            <!--查看频道所有用户列表显示-->
            <ul class="manageChannel_ul"  v-scroll="onScroll" >
                <li class="groupMember_li" v-if="channelUserList[0].uid!==''" v-for="item in channelUserList">
                    <a-row class="groupMemberAdd_ul_row">
                        <a-col :span="4" class="groupMember_li_left">
                            <div class="groupMember_li_ico">
                                <img src="../../assets/drawable-mdpi/avatar.png" width="51" height="50">
                            </div>
                        </a-col>

                        <a-col :span="15" class="groupMember_li_center">
                            <div class="groupMember_li_topText">
                                {{item.name}}
                            </div>
                            <div class="groupMember_li_bottomText">
                                {{item.uid}}
                            </div>
                        </a-col>

                        <a-col :span="5" class="groupMember_li_right">
                            <div class="groupMember_li_rightText_add">
                                <Button class="removeUserClass" icon="ios-trash-outline" @click="removeUser(item.uid)" v-if="isCreator===true">
                                    移除
                                </Button>
                               <Button class="removeUserClass" icon="ios-trash-outline" disabled v-else>
                                   移除
                               </Button>
                            </div>
                        </a-col>
                    </a-row>
                </li>
            </ul>
        </div>

        <!--添加成员到频道的dialog-->
        <el-dialog title="添加频道成员" :visible.sync="addUsersDialog" width="90vw" top="45vw" custom-class="addUsersDialog">
            <!--查看所有可添加到指定频道的用户列表-->
            <div style="border-bottom: 1px solid #e9e9e9;text-align: left;padding-left: 1vw">
                <Checkbox :indeterminate="indeterminate" :value="checkAll" @click.prevent.native="handleCheckAll" class="allSelectClass" style="zoom: 120%">全选</Checkbox>
            </div>
            <ul class="manageChannelDialog_ul"  v-scroll="onScroll" v-loading="loading" >
                <li class="manageChannelDialog_li" v-if="canAddUsersList[0].uid!==null" v-for="item in canAddUsersList">
                    <a-row class="groupMemberAdd_ul_row">
                        <a-col :span="5" class="groupMember_li_left">
                            <div class="groupMember_li_ico">
                                <img src="../../assets/drawable-mdpi/avatar.png" width="51" height="50">
                            </div>
                        </a-col>

                        <a-col :span="16" class="groupMember_li_center">
                            <div class="groupMember_li_topText">
                                {{item.userName}} <span style="font-size: 4vw">{{item.phone}}</span>
                            </div>
                            <div class="groupMember_li_bottomText">
                                {{item.imei}}
                            </div>
                        </a-col>

                        <a-col :span="3" class="groupMember_li_right" style="text-align: center">
                            <div class="groupMember_li_rightText_add">
                                <input type="checkbox" style="zoom: 140%" v-model='checkAllGroup' :value="item.uid" @change="checkAllGroupChange">
                            </div>
                        </a-col>
                    </a-row>
                </li>
            </ul>
            <div slot="footer" class="mc_dialog_footer">
                <el-button @click="addUsersDialog = false">取 消</el-button>
                <el-button type="primary" @click="addUsers">确 定</el-button>
            </div>
        </el-dialog>

        <FooterChaanel v-if="isShowFooter===true"></FooterChaanel>
    </div>

</template>
<style>
    .mc_dialog_footer{
        width: 78vw;
        height: 12vw;
        line-height: 12vw;
        text-align: center;
    }
    .manageChannel_ul{
        padding: 1vw 2vw 0 2vw;
        margin: 0;
        overflow: scroll;
        height: calc(100vh - 78vw);
    }
    .removeUserClass{
        font-size:5vw !important;
        padding: 0.5vw 1vw 0.5vw 1vw !important;;
        background: rgb(237,237,237) !important;;
    }
    .manageChannel_title_row{
        width: 96vw;
        height: 12vw;
        line-height: 12vw;
        text-align: right;
    }
    .manageChannel_title_col{
        height: 12vw;
        line-height: 12vw;
    }
    .manageChannelDialog_ul{
        margin: 0;
        overflow: scroll;
        height: 70vw;
    }
    .manageChannelDialog_li  {
        width: 78vw;
        height: 16vw;
        line-height: 16vw;
        margin:0 0 1vw 0 ;
        float: left;
        list-style: none;
    }
    .addUsersDialog>.el-dialog__body{
        padding: 5px 10px 5px 10px
    }
    .addUsersDialog>.el-dialog__body{
        padding: 0 20px;
    }
    .addUsersDialog>.el-dialog__footer{
        padding: 5px 20px;
    }

</style>
<script>
    import TitleTop from '../../components/TitleTop'
    import TitleMenu from '../../components/TitleMenu'
    import FooterChaanel from "../../components/FooterChaanel";
    import ARow from "ant-design-vue/es/grid/Row";
    import ACol from "ant-design-vue/es/grid/Col";
    import axios from "axios";
    export default {
        name: "SearchChannel",
        components:{ACol, ARow, TitleTop,TitleMenu,FooterChaanel},
        directives: {
            focus: {
                // 指令的定义
                inserted: function (el) {
                    el.focus()
                }
            }
        },
        data() {
            return {
                msg: "Hello Vue.js",
                isShowFooter:true,
                cId:this.$route.params.cId?this.$route.params.cId:"",
                cName:this.$route.params.cName?this.$route.params.cName:"",//频道名称
                currUserId:this.$store.state.intercomList.memberManage.currMember.iId,
                isCreator:this.$route.params.isCreator?this.$route.params.isCreator:false,
                channelUserList : [{"uid":"","name":"","currentChannelId":null,"nick":""}],
                addUsersDialog:false,//添加成员的dialog
                canAddUsersList:[{
                        "username": "",
                        "phone": "",
                        "imei": "",
                        }],//可以被添加至频道的成员列表
                indeterminate: true,
                checkAll: false,
                checkAllGroup: [],
                loading:false,

            }
        },
        mounted() {
            this.getChannelUserList();

        },
        methods:{
            handleCheckAll () {
                if (this.indeterminate) {
                    this.checkAll = false;
                } else {
                    this.checkAll = !this.checkAll;
                }
                this.indeterminate = false;

                if (this.checkAll) {
                    let temp = [];
                    this.canAddUsersList.forEach(f=>{
                        temp.push(f.uid);
                    });
                    this.checkAllGroup = temp;
                } else {
                    this.checkAllGroup = [];
                }
            },
            checkAllGroupChange () {
                let data = this.checkAllGroup;
                if (data.length === this.canAddUsersList.length) {
                    this.indeterminate = false;
                    this.checkAll = true;
                } else if (data.length > 0) {
                    this.indeterminate = true;
                    this.checkAll = false;
                } else {
                    this.indeterminate = false;
                    this.checkAll = false;
                }
            },
            jumpBack(){
                this.clickButton();
                this.$router.go(-1);
            },
            onScroll(){
                this.handleScroll;
            },
            getChannelUserList(){
                this.$apiIntercom.getMembers(this.cId).then(result => {
                    let data = result.data;
                    if (data.code === 200) {
                        this.channelUserList = data.memberlist;//得到uid都是string类型
                    }else{
                        return;
                    }
                }).catch(e =>{
                    console.log(e);
                });
            },
            removeUser(uid){
                //不能移除自己
                if(uid===String(this.currUserId)){
                    this.$toast("当前用户不能移除","short","bottom",-100);
                }else {
                    //移除成员成功后，本地将该用户的信息从集合中删除
                    let memberIndex = this.channelUserList.findIndex(t=>t.uid === uid);
                    let upId = this.cId;
                    let currChannelId = this.$store.state.intercomList.channelManage.currChannel.id;
                    if(memberIndex>-1){
                        this.$apiIntercom.removeMember(this.cId,uid).then(result => {
                            let data = result.data;
                            if (data.code === 200) {
                                this.channelUserList.splice(memberIndex,1);
                                //由于在查看频道所有成员功能，管理频道页面的邀请成员页面，邀请了成员只会触发onChannelUpdated，
                                //回到频道页面人员无变化，所以下面还需根据当前频道的id获取频道下的各人员信息和状态。
                                //判断要邀请成员的频道id和当前id一致，则获取刷新一次当前频道成员信息
                                if(currChannelId === upId){
                                    let success = function(result){
                                        console.log("邀请成员后，频道信息发生改变时获取频道成员",result);
                                    };
                                    let fail = function(e){
                                        console.log(e);
                                    };
                                    let options = {
                                        channelId:currChannelId,//int
                                        currentPageId:0,//int 当前当前页面的id 0页 展示10条，在成员页面需要翻页功能，翻页则+1代表从11条-20...
                                    };
                                    if(typeof (Intercom)!=="undefined") {
                                        Intercom.getChannelAllMember(success, fail, options);
                                    }
                                }else{
                                    return;
                                }
                            }else{
                                return;
                            }
                        }).catch(e =>{
                            console.log(e);
                        });
                    }else{
                        this.$toast("移除失败，请刷新","short","bottom",-100);
                    }
                }

            },
            getCanAddUsersList(){
                this.addUsersDialog = true;
                this.loading = true;
                let gis4_imei = localStorage.getItem('gis4_imei');
                let intercomUserList = [];
                let contactsUserList = [];

                function intercomUserListFun() {
                    return new Promise((resolve,reject)=>{
                        let pageIndex = 1;
                        let pageSize = 100000;
                        me.$apiIntercom.getALLUsers(pageIndex,pageSize).then(result => {
                            let data = result.data;
                            if (data.code === 200) {
                                resolve(data.userlist);
                            }else{
                                return;
                            }
                        }).catch(e =>{
                            reject(e);
                        });
                    })
                }

                function getContactsFun(me) {
                    return new Promise((resolve,reject)=>{
                        me.$api.getContacts(gis4_imei).then((resp)=>{
                            if(resp.data.status ===200){
                                resolve(resp.data.result);
                                /*contactsUserList = resp.data.result;
                                console.log("contactsUserList",contactsUserList);*/
                            }else {
                                reject("获取可添加的对讲联系人其他状态码");
                            }
                        }).catch((error)=>{
                            reject("获取可添加的对讲联系人错误:"+error);
                            /*console.log("获取可添加的对讲联系人错误:"+error);
                            this.loading = false;*/
                        });
                    })
                }
                let me = this;
                Promise.all([intercomUserListFun(me), getContactsFun(me)]).then((result) => {
                    console.log("a1l",result);               //[array1, array2]
                    intercomUserList = result[0];
                    contactsUserList = result[1];
                    this.channelUserList.forEach(v=>{
                        let reIndex = intercomUserList.findIndex(t=>String(t.uid) === String(v.uid));
                        intercomUserList.splice(reIndex,1);
                        console.log("reIndex",reIndex);
                    });
                    console.log("intercomUserList",intercomUserList);

                    // 交集
                    let listIntersection = function(x, y) {
                        let result = [];
                        for (let i = 0; i < y.length; i++) {
                            let temp = y[i];
                            for (let j = 0; j < x.length; j++) {
                                // 普通数组 (temp === clone[j])
                                if (temp.imei === x[j].name) {
                                    result.push(temp);
                                    break;
                                }
                            }
                        }
                        return result;
                    };
                    //console.log("交集",listIntersection(contactsUserList,intercomUserList).length);
                    this.canAddUsersList = listIntersection(intercomUserList,contactsUserList);
                    console.log("this.canAddUsersList",this.canAddUsersList);
                    this.loading = false;

                }).catch((error) => {
                    console.log("all error",error);
                    this.loading = false;
                })



            },
            addUsers(){
                if(this.checkAllGroup.length>0){
                    let members = "";
                    let upId = this.cId;
                    let currChannelId = this.$store.state.intercomList.channelManage.currChannel.id;
                    if(this.checkAllGroup.length>0){
                        this.checkAllGroup.forEach(f=>{
                            members +=f+",";
                        });
                        members = members.substr(0, members.length - 1);//去掉末尾的逗号
                        this.$apiIntercom.addMember(this.cId,members).then(result => {
                            let data = result.data;
                            if (data.code === 200) {
                                this.addUsersDialog = false;
                                this.getChannelUserList();//得到uid都是string类型

                                //由于在查看频道所有成员功能，管理频道页面的邀请成员页面，邀请了成员只会触发onChannelUpdated，
                                //回到频道页面人员无变化，所以下面还需根据当前频道的id获取频道下的各人员信息和状态。
                                //判断要邀请成员的频道id和当前id一致，则获取刷新一次当前频道成员信息
                                if(currChannelId === upId){
                                    let success = function(result){
                                        console.log("邀请成员后，频道信息发生改变时获取频道成员",result);
                                    };
                                    let fail = function(e){
                                        console.log(e);
                                    };
                                    let options = {
                                        channelId:currChannelId,//int
                                        currentPageId:0,//int 当前当前页面的id 0页 展示10条，在成员页面需要翻页功能，翻页则+1代表从11条-20...
                                    };
                                    if(typeof (Intercom)!=="undefined") {
                                        Intercom.getChannelAllMember(success, fail, options);
                                    }
                                }else{
                                    return;
                                }

                            }else{
                                return;
                            }
                        }).catch(e =>{
                            console.log(e);
                            this.$toast("添加频道成员异常","short","bottom",-100);
                            this.addUsersDialog = false;
                        });
                    }



                }
            },
        },
        /*watch: {
            'checkAllGroup': {
                handler: function(val, oldVal) {
                    if (val.length === this.canAddUsersList.length) {
                        this.checkAll = true;
                    } else {
                        this.checkAll = false;
                    }
                },
                deep: true
            }
        },*/
    }
</script>

<style>

</style>